<?php

namespace app\api\controller;

use app\services\ExchangeService;
use support\Db;
use support\Request;

class ExchangeApplyController
{
    public function list(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $status = $request->post('status', -1);
            $keyword = $request->post('keyword', '');

            $list = ExchangeService::applyList($page, 10, $status, $keyword);

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function detail(Request $request)
    {
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            $list = ExchangeService::applyDetail($id);

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function cancel(Request $request)
    {
        Db::beginTransaction();
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            ExchangeService::applyCancel($id);

            Db::commit();
            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }
}